/**
 * 产品添加
 */
var comValidform = null;
var returnStatus = false;
var productInfoAdd = {
	dataCache : null,
    jjsId:'15',
    getSysParam:function () {
        var url = 'mgr/parameterCtrl/getParameter?name=JJS_ID';
        var cb =function (data) {
            if (data.resultCode == 200) {
                productInfoAdd.jjsId = data.result.value01;
            }
        }
        sendApiNoLoad(url, null, cb, 'GET');
    },
	getCompanyResource : function() {
		var url = 'mgr/companyCtrl/list';
		var params = {
			'curPage' : 0,
			'pageSize' : 9999,
			'id' : null,
			'name' : null
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择发行方</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + '</option>';
				}
				$('select[name="issuerId"]').append(option);
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');

	},
	getProParResource : function() {
		var url = 'mgr/ProductInfoCtrl/getParProdInfoList';
		var params = {
			'prodTopType':2
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择产品父标</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
						+ singleObj.name + '</option>';
				}
				$('select[name="parId"]').append(option);
			}
		};
		sendApiNoLoadSync(url, params, cb, 'POST');

	},
	getHCAddRateResource : function() {
		var url = 'mgr/ProductInfoCtrl/getHCAddRateProdList';
		var params = {};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择加息产品</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
						+ singleObj.name + '</option>';
				}
				$('select[name="addRateProduct01"]').append(option);
				$('select[name="addRateProduct02"]').append(option);
			}
		};
		sendApiNoLoadSync(url, params, cb, 'GET');
	},
	
	getContractResource : function() {
		var url = 'mgr/agreementCtrl/list';
		var params = {
			'curPage' : 0,
			'pageSize' : 9999,
			'id' : null,
			'name' : null
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.id + '">'
							+ singleObj.name + "--" + singleObj.id + '</option>';
				}
                $('.agreements').append(option);
                //初始化下拉多选框
                $(".agreements").SumoSelect({
                    csvDispCount: 5,
                    captionFormat: '{0} 个被选中'
                });

                $(".agreements").change(function(){
                    var selecteds=$(".agreements option:selected").length;
                    if(selecteds==0){
                        $("#contractId").val("");
                    }else{
                        $("#contractId").val("1");
                    }

                })
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');

	},

	
	startEvent : function() {
		$("select[name='discount']").change();
		
		$("#recordTab ul").idTabs();
		var introduceUE = UE.getEditor('introduce', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		var incomeUE = UE.getEditor('income', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		var product_descriptionUI = UE.getEditor('product_description', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		var riskctrlUE = UE.getEditor('riskctrl', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});
		
		var signflowUE = UE.getEditor('signflow', {
			initialFrameHeight : 340,
			initialFrameWidth : 898
		});

		comValidform = $(".com-addForm").Validform({
			datatype : {
				"m0-2" : /^[0-9]+(.[0-9]{1,2})?$/
			},
			tiptype : 2,
			tipSweep : true,
			beforeSubmit : function(curform) {
				var url = 'mgr/ProductInfoCtrl/saveProductInfo';
				var params = jsUtils.serializeJson($('.com-addForm'));
				var introduce = introduceUE.getContent();
				params.introduce = introduce;

				var income = incomeUE.getContent();
				params.income = income;

				var riskctrl = riskctrlUE.getContent();
				params.riskctrl = riskctrl;
				
				var signflow = signflowUE.getContent();
				params.signflow = signflow;

				var description = product_descriptionUI.getContent();
				params.productDescription = description;
				
				if(params.discount!=1){
					delete params.discountDate,
					delete params.discountBeginDate;
					delete params.discountEndDate;
					delete params.discountRate;
				}
				
				if(params.proDividendDate == null || params.proDividendDate == ''){
					delete params.proDividendDate;
				}
				
				if(params.proDividStartDate == null || params.proDividStartDate == ''){
					delete params.proDividStartDate;
				}

				if(params.buyChannel == 2 && (params.creditorPhoneNum == null || params.creditorPhoneNum =="")){
					alert("募集账号没有填写，填写后再提交");
					return false;
				}

				if(params.saleType == 4 && (params.addRate == null || params.addRate == '')){
					alert("额外收益类产品必须填写产品额外收益，填写后再提交");
					return false;
				}

				if(parseInt(params.subscriptionOrigin) < parseInt(params.minAppendAccount)) {
					alert("认购起点必须大于或等于最低追加金额");
					return false;
				}
                if((params.subscriptionOrigin) % (params.minAppendAccount) != 0) {
                    alert("认购起点必须能整除最低追加金额");
                    return false;
                }
				
				//默认为非热销
				params.hotSale="0";

				/*把选择的合同转成数组传到后台（修重BUG：插件如果选择单个结果不是数组，多个又是数组）*/
                var agreements = new Array();
                $(".agreements option:selected").each(function(){
                    agreements.push($(this).val())
                })
                params.agreements = agreements;

				var cb = function(data) {
					alert(data.msg);
					// 成功返回
					if (data.resultCode == '200') {
						// 关闭窗口并刷新数据
						art.dialog.close();
						returnStatus = true;
					}
				};
				sendApiNoLoadSync(url, params, cb, 'POST');
				return false;
			}
		});
	},
	
	bindEvent: function() {
		//添加贴息事件
		$("select[name='discount']").change(function() {
			if ($("select[name='discount']").val() == 1) {
				$("input[name='discountRate']").attr('type', 'text');
				$("input[name='discountRate']").attr('ignore', '');
				$("input[name='discountEndDate']").attr('type', 'text');
				$("input[name='discountEndDate']").attr('ignore', '');
			} else {
				$("input[name='discountRate']").attr('type', 'hidden');
				$("input[name='discountRate']").attr('ignore', 'ignore');
				$("input[name='discountEndDate']").attr('type', 'hidden');
				$("input[name='discountEndDate']").attr('ignore', 'ignore');
			}
		});

        //选择发行方时，如果是贵州场外，挂牌号、备案号不能为空
        $('.com-addForm select[name="issuerId"]').change(function () {
            if(checkContain(productInfoAdd.jjsId,$(this).val()) && $('#com-addForm input[name="listingNumber"]').val() == ""){
                /** 挂牌号 */
            	$('#com-addForm input[name="listingNumberHidden"]').val("");
            	/** 备案号 */
                $('#com-addForm input[name="licenseNumberHidden"]').val("");
            }else {
            	/** 挂牌号 */
                $('#com-addForm input[name="listingNumberHidden"]').val("1");
                /** 备案号 */
                $('#com-addForm input[name="licenseNumberHidden"]').val("1");
            }
        });
        $('#com-addForm input[name="listingNumber"]').blur(function () {
            if(checkContain(productInfoAdd.jjsId,$('.com-addForm select[name="issuerId"]').val()) && $(this).val() == ""){
                $('#com-addForm input[name="listingNumberHidden"]').val("");
            }else {
                $('#com-addForm input[name="listingNumberHidden"]').val("1");
            }
        });
        /** 绑定备案号失去焦点事件，如果是金交所，必填 */
        $('#com-addForm input[name="licenseNumber"]').blur(function () {
            if(checkContain(productInfoAdd.jjsId,$('.com-addForm select[name="issuerId"]').val()) && $(this).val() == ""){
                $('#com-addForm input[name="licenseNumberHidden"]').val("");
            }else {
                $('#com-addForm input[name="licenseNumberHidden"]').val("1");
            }
        });



	},

	init : function() {
        productInfoAdd.getSysParam();
		productInfoAdd.bindEvent();
		productInfoAdd.getCompanyResource();
		productInfoAdd.getContractResource();
		productInfoAdd.getProParResource();
		productInfoAdd.getHCAddRateResource();
		productInfoAdd.startEvent();
		
	}
}
$(document).ready(function() {
	productInfoAdd.init();
});
function submitForm() {
	comValidform.submitForm();
	return returnStatus;
}

/**
 * 检查value有没有包含key值
 * @param value
 * @param key
 */
function checkContain (value,key) {
    var array = value.split(",");
    var result = false;
    array.forEach(function (val) {
        if(val == key){
            result = true;
        }
    })

    return result;
}


